package com.dollkey.packagemanager;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

public class FilesSystemActivity extends AppCompatActivity {

    private static final String TAG = "FilesSystemActivity";
    private TextView mTitle;
    private File mFile;
    private List<File> mFileList;
    private CommonAdapter<File> mAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.aty_files_system);
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        mTitle = findViewById(R.id.text);
        mTitle.setOnClickListener(v -> {
            back();
        });
        mFileList = new ArrayList<>();
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        mAdapter = new CommonAdapter<File>(this, R.layout.item_file, mFileList) {
            @Override
            protected void convert(ViewHolder holder, File file, int position) {
                holder.setText(R.id.type, file.isDirectory() ? "文件夹" : "文件");
                holder.setText(R.id.size, formatFileSize(file.isDirectory() ? getFolderSize(file) : file.length()));
                holder.setText(R.id.path, file.getName());
                if (file.isFile() &&
                        (file.getName().endsWith(".jpg")) ||
                        file.getName().endsWith(".jpeg") ||
                        file.getName().endsWith(".png") ||
                        file.getName().endsWith(".gig")) {
                    ImageView view = holder.getView(R.id.image);
                    Glide.with(view).load(file).into(view);
                }
                holder.itemView.setOnClickListener(v -> {
                    if (file.isDirectory()) {
                        File[] files = file.listFiles();
                        mFileList.clear();
                        mFileList.addAll(Arrays.asList(files));
                        mTitle.setText(file.getAbsolutePath());
                        mFile = file;
                        mAdapter.notifyDataSetChanged();
                    } else {
//                        openFile(file);
                    }
                });
            }
        };
        recyclerView.setAdapter(mAdapter);
        new Thread(() -> {
            String s = Environment.getExternalStorageDirectory() + "/";
            File file = new File(s);
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                mFileList.clear();
                mFileList.addAll(Arrays.asList(files));
                mTitle.setText(file.getAbsolutePath());
                mFile = file;
                mAdapter.notifyDataSetChanged();
            }
        }).start();
    }

    @Override
    public void onBackPressed() {
        if (back()) {
            super.onBackPressed();
        }
    }

    private boolean back() {
        if (mFile != null) {
            File parentFile = mFile.getParentFile();
            if (parentFile != null) {
                File[] files = parentFile.listFiles();
                mFileList.clear();
                mFileList.addAll(Arrays.asList(files));
                mAdapter.notifyDataSetChanged();
                mTitle.setText(parentFile.getAbsolutePath());
                mFile = parentFile;
            }
            return false;
        }
        return true;
    }

    /**
     * 使用自定义方法打开文件
     */
    public void openFile(File file) {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //  此处注意替换包名，
            Uri contentUri = FileProvider.getUriForFile(this, "com.job.oa.fileprovider", file);
            Log.e("file_open", " uri   " + contentUri.getPath());
            intent.setDataAndType(contentUri, getMimeTypeFromFile(file));
//            intent.setDataAndType(contentUri, "image/*");
        } else {
            intent.setDataAndType(Uri.fromFile(file), getMimeTypeFromFile(file));//也可使用 Uri.parse("file://"+file.getAbsolutePath());
        }

        //以下设置都不是必须的
        intent.setAction(Intent.ACTION_VIEW);// 系统根据不同的Data类型，通过已注册的对应Application显示匹配的结果。
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//系统会检查当前所有已创建的Task中是否有该要启动的Activity的Task
        //若有，则在该Task上创建Activity；若没有则新建具有该Activity属性的Task，并在该新建的Task上创建Activity。
        intent.addCategory(Intent.CATEGORY_DEFAULT);//按照普通Activity的执行方式执行
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(intent);
    }

    /**
     * 获取文件夹大小
     *
     * @param file File实例
     * @return long
     */
    private long getFolderSize(File file) {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isDirectory()) size = size + getFolderSize(fileList[i]);
                else size = size + fileList[i].length();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 使用自定义方法获得文件的MIME类型
     */
    public static String getMimeTypeFromFile(File file) {
        String type = "*/*";
        String fName = file.getName();
        //获取后缀名前的分隔符"."在fName中的位置。
        int dotIndex = fName.lastIndexOf(".");
        if (dotIndex > 0) {
            //获取文件的后缀名
            String end = fName.substring(dotIndex, fName.length()).toLowerCase(Locale.getDefault());
            //在MIME和文件类型的匹配表中找到对应的MIME类型。
            HashMap<String, String> map = MyMimeMap.getMimeMap();
            if (!TextUtils.isEmpty(end) && map.keySet().contains(end)) {
                type = map.get(end);
            }
        }
        Log.i("bqt", "我定义的MIME类型为：" + type);
        return type;
    }

    private void scanFiles(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null) {
                for (File f : files) {
                    scanFiles(f);
                }
            }
        }
        Log.e(TAG, formatFileSize(file.length()) + "__" + file.getAbsolutePath());
    }

    /**
     * 转换文件大小
     */
    public static String formatFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.0");
        String fileSizeString;
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }
}
